<template>
  <el-select :value="defaultValue"  :clearable="isAll" :disabled="disabled" @change="handleChange" :style="selectStyle">
    <el-option
      v-for="item in options"
      :key="item.value"
      :label="item.name"
      :value="item.code"
      :disabled="item.disabled">
    </el-option>
  </el-select>
</template>
<script>
import { getOptionsByCodeType } from '@/utils/getOptionis'
export default {
  name: 'CustomCombox',
  data() {
    return {
      options: [],
      defaultValue: ''
    }
  },
  props: {
    codeType: {
      type: String,
      required: true
    },
    isAll: {
      type: Boolean,
      default: function() {
        return true
      }
    },
    disabledValues: {
      type: Array
    },
    onlyNeedValues: {
      type: Array
    },
    value: {
      type: String
    },
    disabled: {
      type: Boolean
    },
    isMultiple: {
      type: Boolean,
      default: () => false
    },
    selectStyle: {
      type: Object,
      required: false,
      default: function() {
        return { width: '100%' }
      }
    }

  },
  methods: {
    handleChange(val) {
      this.$emit('input', val)
    },
    init() {
      getOptionsByCodeType(this.codeType).then(response => {
        const data = response.data.data
        if (data) {
          const tmp = []
          const supportType = []

          data.forEach(element => {
            const elementTmp = element
            elementTmp.disabled = this.disabledValues && this.disabledValues.indexOf(element.code) !== -1
            if (this.onlyNeedValues && this.onlyNeedValues.length > 0) {
              if (this.onlyNeedValues.indexOf(element.code) !== -1) {
                tmp.push(elementTmp)
              }
            } else {
              tmp.push(elementTmp)
            }
            if (elementTmp.disabled === false || !elementTmp.disabled) {
              supportType.push(element)
            }
          })

          this.options = tmp
          if (!this.isAll) {
            if (supportType.length > 0) {
              let firstVal = supportType[0].code
              if (this.onlyNeedValues && this.onlyNeedValues.length > 0) {
                firstVal = this.onlyNeedValues[0]
              }
              this.defaultValue = this.value || firstVal
              this.$emit('input', this.defaultValue)
            }
          }
        }
      })
    }
  },
  created() {
    this.defaultValue = this.value
    this.init()
  },
  watch: {
    value() {
      this.defaultValue = this.value
    },
    codeType() {
      this.init()
    }
  }
}
</script>
